import React from 'react';
import {connect} from 'react-redux';
import TodoItem from './todoItem';
import {toggleTodo, removeTodo} from "../actins";
import {FilterTypes} from "../../filterTypes";

const TodoList = ({todos, toggleTodo, removeTodo}) => {
    return (
        <ul className="todo-list">
            {
                todos.map((item) => (
                    <TodoItem
                        key={item.id}
                        id={item.id}
                        text={item.text}
                        completed={item.completed}
                        onToggle={toggleTodo}
                        onRemove={removeTodo}/>
                ))
            }
        </ul>
    )
};

const selectVisibleTodos = (todos, filter) => {
    switch (filter) {
        case FilterTypes.All:
            return todos;
        case FilterTypes.COMPLETED:
            return todos.filter(item => item.completed);
        case FilterTypes.UNCOMPLETED:
            return todos.filter(item => !item.completed);
        default:
            return new Error('unsupported filter');
    }
};

const mapStateToProps = (state) => {
    return {
        todos: selectVisibleTodos(state.todos, state.filter)
    };
};

const mapDispatchToProps = {
    toggleTodo: toggleTodo,
    removeTodo: removeTodo
};

export default connect(mapStateToProps, mapDispatchToProps)(TodoList);